from time import sleep
from zlib import *
from threading import Thread
from socket import (SO_RCVLOWAT, socket, AF_INET, SOCK_DGRAM, SOL_SOCKET, SO_BROADCAST)
from tkinter import Tk, BooleanVar, Button, Label, Tk
from PIL.ImageGrab import grab
from PIL import Image

sock = socket(AF_INET, SOCK_DGRAM)
sock.setsockopt(SOL_SOCKET, SO_BROADCAST, True)

IP = "255.255.255.255"
PORT = 22222
BUFFER_SIZE = 1024

im = grab()

w, h = im.size
# 把图片转换为字节，压缩后传输，减少带宽占用

im_bytes = im.tobytes()
im_compress = compress(im.tobytes())
b = Image.frombytes("RGBA", im.size, im_bytes)
b.show()


# 通知局域网内用户开始发送
sock.sendto(b'start', (IP, PORT))

# 分块发送，以免字节太长无法发送
cnt = 0
for i in range(len(im_compress) // BUFFER_SIZE + 1):

    start = i * BUFFER_SIZE
    end =  start + BUFFER_SIZE
    # print(im_compress[start:end], end='')
    sock.sendto(im_compress[start:end], (IP, PORT))
    sleep(0.00001)
    cnt += 1

# 发送完毕
sock.sendto(b'_over' + str((w, h)).encode(), (IP, PORT))

sock.close()